package org.lyg.shiro.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.lyg.domain.User;
import org.lyg.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 用户是否有效过滤，如果用户账户被锁定或者被禁用则无法通过验证
 */
@Component
public class UserValidFilter extends AccessControlFilter {
    @Autowired
    IUserService userService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        User user = (User) subject.getPrincipal();
        if (user != null) {
            User src = userService.getUserByName(user.getName());
            if (src != null && src.getVersion() != null && !src.getVersion().equals(user.getVersion())) {
                System.out.println("用户信息失效！");
                subject.logout();
            }
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }
}
